package cn.com.idmy.cloud.config;

import cn.com.idmy.cloud.GlobalNameFilter;
import cn.com.idmy.cloud.GlobalValueFilter;
import cn.com.idmy.cloud.advice.CloudGlobalResponseHandler;
import cn.com.idmy.cloud.advice.GlobalResponseHandler;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

public class GlobalWebConfig implements WebMvcConfigurer {
    private final FastJsonHttpMessageConverter converter;

    {
        var cfg = new FastJsonConfig();
        cfg.setWriterFilters(new GlobalNameFilter(), new GlobalValueFilter());
        converter = new FastJsonHttpMessageConverter();
        converter.setSupportedMediaTypes(List.of(MediaType.APPLICATION_JSON));
        converter.setFastJsonConfig(cfg);
    }

    @Override
    public void configureMessageConverters(@NotNull List<HttpMessageConverter<?>> converters) {
        converters.addFirst(converter);
    }

    @Bean
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
        return converter;
    }

    @Bean
    @ConditionalOnClass(name = "feign.RequestInterceptor")
    public CloudGlobalResponseHandler cloudGlobalResponseHandler() {
        return new CloudGlobalResponseHandler();
    }

    @Bean
    @ConditionalOnMissingClass("feign.RequestInterceptor")
    public GlobalResponseHandler globalResponseHandler() {
        return new GlobalResponseHandler();
    }
}
